<template>
      <q-dialog v-model="depotHistory">
      <MyBigDialog title="Car Logs">
        <div v-if="car_logs.length>0">
          <ScrollArea >
            <div v-for="(item, index) in car_logs" :key="index">
              <LogCard class="" :item="item"></LogCard>
              <q-separator inset></q-separator>
            </div>
          </ScrollArea>
        </div>
        <div v-else class="q-pa-md">
          No data found...
        </div>
      </MyBigDialog>
    </q-dialog>
  <div class="my-card">
    <div class="q-gutter-y-md">
      <div class="page-header q-pa-sm fal">Depot</div>
      <q-card class="search-css card-radius q-pa-sm">
        <div class="row">
          <div class="sub-header col-12 q-pa-sm">Train / Track <q-btn icon="history" flat color="blue-9" @click="onDepotHistory"></q-btn></div> 
          <i class="col-12 q-pa-sm"
            >Please scan the QR code on the train, track side, or location to
            find out equipment.</i
          >
          <div class="text-sm col-12 q-pa-sm">Train / Track / Car:</div>
          <div class="text-sm col-10 q-pa-sm items-center">
            <!-- <q-input
              class="input-css"
              borderless
              :dense="true"
              v-model="location"
            ></q-input> -->
            <q-select
              class="input-css q-ma-sm col-8"
              label="Location"
              :dense="true"
              borderless
              v-model="location"
              :options="locationOptions"
              use-input
              @filter="filterLocFn"
            ></q-select>
          </div>
          <div class="text-sm q-pa-sm col-2 fac">
            <q-icon
              name="qr_code"
              size="40px"
              color="primary"
              class="cursor-pointer"
              @click="scanDiag = true"
            ></q-icon>
            <q-dialog v-model="scanDiag">
              <OpenCam @submit="(v) => onSubmit(v)"></OpenCam>
            </q-dialog>
          </div>

          <div v-if="msg" class="warning">
            {{ 'NO RECORD. PLEASE TRY AGAIN OR CHECK' }}
          </div>
          <q-card-actions align="center" class="action col-12">
            <q-btn class="default-btn" @click="search">Search</q-btn>
          </q-card-actions>
        </div>
      </q-card>
      <q-card-actions class="justify-end">
        <q-btn class="yellow-btn q-mx-sm" @click="popup=true"
          >Fitment</q-btn
        >

        <q-icon
          class="cursor-pointer info-icon"
          name="info"
          color="black"
          size="sm"
          @click="small = true"
        />
      </q-card-actions>
      <div class="">
        <i class="q-pa-sm text-body col-12">
          Please click the new fitment button to fit the equipment to the train,
          track side or location
        </i>
      </div>

      <StatusDialog v-model="small"></StatusDialog>
      <div class="row" v-if="parents">
        <i class="q-pa-sm text-body col-12">
          Please click the defitment button to remove the equipment from the
          train, track side or location.
        </i>
        <i class="q-pa-sm text-body col-12">
          Please click below equipment to update the card belonging
        </i>
      </div>
      <div class="col-12" v-if="parents">
        <div v-for="(parent, index) in parents" :key="index">
          <div class="text-h6 row justify-between">
            {{
              'Short Description: ' +
              parent.description +
              ', Serial No: ' +
              parent.serial_no +
              ' , Car:' +
              getDescription(parent.car)
            }}
            <!-- {{ 'parent version sw: '+parent.sw_ver }}
            {{ 'parent version hw: '+parent.hw_ver }} -->

            <q-btn
              class="blue-btn q-mx-lg"
              @click="defitCar(parent.stock_code, parent.serial_no)"
              >Defitment</q-btn
            >
          </div>

          <q-card
            class="q-ma-md cursor-pointer card-radius"
            :class="[
              getPartsStatus(
                parent.serial_no,
                parent.stock_code,
                parent.sw_ver,
                parent.hw_ver
              )?.includes('fail')
                ? 'fail'
                : getPartsStatus(
                    parent.serial_no,
                    parent.stock_code,
                    parent.sw_ver,
                    parent.hw_ver
                  )?.includes('pass')
                ? 'pass'
                : getPartsStatus(
                    parent.serial_no,
                    parent.stock_code,
                    parent.sw_ver,
                    parent.hw_ver
                  ),
            ]"
            @click="
              openDiag(
                parent.id,
                parent.stock_code,
                parent.serial_no,
                parent.car
              )
            "
          >
            <PartsMap v-if="parent" mode="depot" :item="parent"> </PartsMap>
          </q-card>
          <q-tooltip
            class="bg-indigo"
            anchor="bottom right"
            self="center middle"
          >
            <!-- {{
              getPartsStatus(
                parent.serial_no,
                parent.stock_code,
                parent.sw_ver,
                parent.hw_ver
              )
            }} -->
            <div
              v-for="(s, index) in getPartsStatus(
                parent.serial_no,
                parent.stock_code,
                parent.sw_ver,
                parent.hw_ver
              )?.split(',')"
              :key="index"
            >
              {{ s }}
            </div>
          </q-tooltip>
        </div>
      </div>

      <q-dialog  v-model="popup">
        <FitmentForm
          mode="fitment"
          @update="(string) => update(string)"
        ></FitmentForm>
      </q-dialog>
      <q-dialog v-model="defitPopup">
        <FitmentForm
          mode="defitment"
          :stock_code="editRow.stock_code"
          :serial_no="editRow.serial_no"
          @update="(string) => update(string)"
        ></FitmentForm>
      </q-dialog>
      <q-dialog class="depot-dig" full-width full-height v-model="parentDiag">
        <MyBigDialog
          title="Fitment/Defitment"
          >
          <!-- :content="`Short Description: ${short_description}, Serial No: ${serial_no}, Car:${p_car}`" -->
          <ChildItemList
            @update-child="updateSearch"
            v-if="part"
            :partItem="part"
            :style="'card'"
          ></ChildItemList>
        </MyBigDialog>
      </q-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import PartsMap from 'src/components/PartsMap.vue';
import OpenCam from 'src/components/OpenCam.vue';
import { getPartsStatus } from '../utils/getPublic';
import FitmentForm from 'src/components/depot/FitmentForm.vue';
import { computed, ref, watch } from 'vue';
import { getDepotParts } from 'src/services/depotService';
import { EventLogInterface, Parent, QRLocationMapI } from 'src/services/type';
import { getPartDetailData } from 'src/services/partsService';
import ChildItemList from 'src/components/partsMaster/ChildItemList.vue';
import MyBigDialog from 'src/components/container/MyBigDialog.vue';
import StatusDialog from 'src/components/StatusDialog.vue';
import { useVersionStore } from 'src/stores/versionStore';
import { parseLocationQR } from 'src/utils/parseQRCodeUtils';
import { listqrmap } from 'src/services/qrMapLocationService';
import { useQuasar } from 'quasar';
import ScrollArea from 'src/components/ScrollArea.vue';

import LogCard from 'src/components/log/LogCard.vue'
import { getDepotLogByLocation } from 'src/services/activityLogService';

import {
  Loading,

  // optional!, for example below
  // with custom spinner
  QSpinnerGears
} from 'quasar'

const versionStore = useVersionStore();
versionStore.init();
const scanDiag = ref(false);
const msg = ref(false);
const location = ref('');
const popup = ref(false);
const defitPopup = ref(false);

const stock_code = ref('');
const serial_no = ref('');
const p_car = ref('');
const short_description = ref('');
const small = ref(false);
const editRow = ref();
const parents = ref<Parent[]>();

const $q = useQuasar()

const locationOptions = ref([]);
const locationStringOptions = ref([]);

const locationQRMap = new Map();
const locationDescMap = new Map();

async function initLocationOptions() {
  const res = await listqrmap();
  console.log(res.data);
  if (res.data) {

    locationOptions.value = res.data.map((i: QRLocationMapI) => {
      locationDescMap.set(i.category + '-' +i.train , i)
      locationQRMap.set(i.description, i);
      return i.description;
      
    });
    // locationOptions.value = res.data.map(v=>v.description)
    locationStringOptions.value = [...locationOptions.value];
  }
}



initLocationOptions();
const part = ref();
const parentDiag = ref(false);
async function openDiag(id: number, sc: string, sn: string, car: string) {
  const res = await getPartDetailData(id);
  part.value = res.data;
  parentDiag.value = true;
  stock_code.value = sc;
  serial_no.value = sn;
  if (car) {
    p_car.value = car;
  }

  short_description.value = res.data.description
  console.log(part.value);
}

async function search() {
  Loading.show()
  console.log(location.value);
  parents.value = []
  let locationCode = ''
  const locationmap = locationQRMap.get(location.value)
  if (locationmap){
    console.log(locationmap);
    
    locationCode = locationmap.category + '-' + locationmap.train
  }

  console.log('locationCode', locationCode);

  const res = await getDepotParts(locationCode);
  
  if (res.data) {
    console.log(res.data);
    // const d = [...res.data];
    // const arr = d.filter((item: Parent) => {
    //   return Object.keys(item.child).length > 0;
    // });
    parents.value = res.data
  }
  Loading.hide()
}

function showLoading() {
  $q.loading.show({
    message: 'Doing something. Please wait...',
    boxClass: 'bg-grey-2 text-grey-9',
    spinnerColor: 'primary',
  });
}


function updateSearch() {
  search();
}

function defitCar(stock_code: string, serial_no: string) {
  editRow.value = { stock_code, serial_no };
  defitPopup.value = true;
}

function update(string: string) {
  location.value = string;

  search();
  popup.value = false;
  defitPopup.value = false;
}

async function onSubmit(string: string) {
  scanDiag.value = false;
  const formatString = await parseLocationQR(string);

  if (formatString) {
    console.log('formatString', formatString);
    location.value = formatString;
  }

  search();
}

function getDescription(car: string){
  const locationmap = locationDescMap.get(car)
  if (locationmap){
    return locationmap.description
  }
  return car
}

const car_logs = ref<EventLogInterface[]>([])
const depotHistory = ref(false)


async function onDepotHistory() {
  const locationmap = locationQRMap.get(location.value)

  let locationCode = ''

  if (locationmap){
    locationCode = locationmap.category + '-' + locationmap.train
    const res = await getDepotLogByLocation(locationCode)
    car_logs.value = res
    depotHistory.value = true
  }else{
    const res = await getDepotLogByLocation('')
    car_logs.value = res
    depotHistory.value = true
  }
}

function filterLocFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      locationOptions.value = [...locationStringOptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    locationOptions.value = locationStringOptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}
</script>

<style scoped>
.card-one {
  padding-right: 15px;
}

.content {
  display: flex;
  justify-content: space-between;
  background-color: #eef4fa;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 10px;
}

.warning {
  color: red;
  font-weight: bold;
  text-align: center;
  width: -webkit-fill-available;
  padding-top: 20px;
}
</style>
